<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserBoxVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- //用户列表 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="currentStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="openEditUserInfoDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserInfo(scope.row.id)"
            ></el-button>
            <!-- 消息提示 -->
            <el-tooltip effect="dark" content="设置角色" placement="top" :enterable="false">
              <!-- 设置角色按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页部分 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserBoxVisible"
      width="50%"
      @close="HandleDialogClose"
    >
      <!-- 对话框主体 -->
      <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserBoxVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- //修改用户对话框主体部分 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户角色对话框 -->
    <el-dialog
      title="设置角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClose"
    >
      <!-- 对话框主体 -->
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>
          选择角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <!-- 对话框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    //自定义邮箱校验规则
    var checkEmail = (rule, value, cb) => {
      const reg = /^\w+@[a-z0-9]+\.[a-z]{2,4}$/
      if (reg.test(value)) return cb()
      cb(new Error('邮箱格式不正确!'))
    }
    //自定义手机号校验规则
    var checkMobile = (rule, value, cb) => {
      const reg = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
      if (reg.test(value)) return cb()
      cb(new Error('手机号格式不正确!'))
    }
    return {
      //获取用户列表参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      //用户列表
      userList: [],
      //用户总数
      total: 0,
      // 控制添加用户对话框显示隐藏
      addUserBoxVisible: false,
      // 控制编辑用户对话框的显示和隐藏
      editUserDialogVisible: false,
      // 表单输入框数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单验证数据
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //编辑用户表单数据
      editForm: {},
      //编辑用户对话框验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制设置用户角色对话框的显示和隐藏
      setRoleDialogVisible: false,
      //要被设置角色的用户信息
      userInfo: {},
      // 用于保存角色信息
      roleList: [],
      // 被选中的角色的ID值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    //请求用户数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败!')
      //获取用户列表
      this.userList = res.data.users
      //获取用户总数
      this.total = res.data.total
      console.log(res)
    },
    //一页数据量
    handleSizeChange(val) {
      //改变一页数据数量
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    //当前页码改变时触发
    handleCurrentChange(val) {
      // 改变当前页码
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    //当前用户状态改变时触发
    async currentStateChange(userInfo) {
      //通过put请求修改数据库中的数据
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败!')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 关闭对话框事件
    HandleDialogClose() {
      //重置表单
      this.$refs.addUserRef.resetFields()
    },
    // 添加用户事件
    addUser() {
      // 提交表单预校验
      this.$refs.addUserRef.validate(async valid => {
        if (!valid) return this.$message.error('添加用户验证失败！')
        // 发起数据请求
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) return
        //添加成功隐藏对话框
        this.addUserBoxVisible = false
        // 显示添加成功提示
        this.$message.success('添加用户成功！')
        //添加用户成功后重新请求用户列表
        this.getUserList()
      })
    },
    //打开用户编辑对话框
    async openEditUserInfoDialog(id) {
      //显示修改用户对话框
      this.editUserDialogVisible = true
      //接收要修改的用户数据
      const { data: res } = await this.$http.get('/users/' + id)
      //判断用户数据是否接收成功
      if (res.meta.status !== 200) {
        return this.$message.error('查询数据失败！')
      }
      this.editForm = res.data
    },
    //监听编辑对话框的关闭
    editDialogClose() {
      //重置表单
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('表单验证不通过！')
        }
        //进行数据请求修改用户数据
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        //验证用户数据是否成功
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户数据失败！')
        }
        //关闭对话框
        this.editUserDialogVisible = false
        //更新用户数据
        this.getUserList()
        //弹出修改用户数据成功提示框
        this.$message.success('修改用户数据成功！')
      })
    },
    //删除用户信息且弹窗选择是否删除
    async removeUserInfo(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除用户信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      //如果确认，将返回confirm
      //如果取消，将返回cancel
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除!')
      //接收删除用户信息返回的数据
      const { data: res } = await this.$http.delete('users/' + id)
      //判断用户是否删除成功
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      //提示删除用户成功！
      this.$message.success('删除用户成功！')
      //成功之后刷新用户列表
      this.getUserList()
    },
    //显示设置角色对话框
    async showSetRoleDialog(user) {
      // 保存要设置角色的用户数据
      this.userInfo = user
      // console.log(user)
      // 获取角色信息
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色信息失败！')
      this.roleList = res.data
      // 显示设置角色对话框
      this.setRoleDialogVisible = true
    },
    // 实现分配角色
    async setRole() {
      //验证是否已选择角色
      if (!this.selectedRoleId)
        return this.$message.error('请选择要分配的角色！')
      //通过数据请求实现分配角色
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      // console.log(this.userInfo.id)
      // console.log(res)
      // 验证分配角色是否成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 提示分配角色成功
      this.$message.success('分配角色成功！')
      //更新用户列表
      this.getUserList()
      // 关闭对话框
      this.setRoleDialogVisible = false
    },
    // 监听设置角色对话框关闭
    setRoleDialogClose() {
      // 重置下拉选择数据
      this.selectedRoleId = ''
    }
  }
}
</script>

<style lang="scss" scoped></style>
